package com.lfy.fyadmin.util;

import com.lfy.fyadmin.entity.Permission;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 权限树工具类
 * 用于权限数据的可视化和调试
 */
public class PermissionTreeUtil {
    
    /**
     * 打印权限树结构
     * @param permissions 权限列表
     */
    public static void printPermissionTree(List<Permission> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            System.out.println("权限列表为空");
            return;
        }
        
        System.out.println("=== 权限树结构 ===");
        List<Permission> rootPermissions = permissions.stream()
            .filter(p -> p.getParentId() == null)
            .sorted((p1, p2) -> {
                if (p1.getSort() == null && p2.getSort() == null) return 0;
                if (p1.getSort() == null) return 1;
                if (p2.getSort() == null) return -1;
                return p1.getSort().compareTo(p2.getSort());
            })
            .collect(Collectors.toList());
        
        for (Permission root : rootPermissions) {
            printPermissionNode(root, permissions, 0);
        }
        System.out.println("==================");
    }
    
    /**
     * 递归打印权限节点
     */
    private static void printPermissionNode(Permission permission, List<Permission> allPermissions, int level) {
        String indent = "  ".repeat(level);
        String typeStr = getTypeString(permission.getType());
        String statusStr = permission.getStatus() == 1 ? "启用" : "禁用";
        
        System.out.printf("%s├─ [%d] %s (%s) - %s - %s%n", 
            indent, permission.getId(), permission.getName(), 
            permission.getCode(), typeStr, statusStr);
        
        if (permission.getPath() != null) {
            System.out.printf("%s   路径: %s%n", indent, permission.getPath());
        }
        
        if (permission.getIcon() != null) {
            System.out.printf("%s   图标: %s%n", indent, permission.getIcon());
        }
        
        // 查找子权限
        List<Permission> children = allPermissions.stream()
            .filter(p -> Objects.equals(p.getParentId(), permission.getId()))
            .sorted((p1, p2) -> {
                if (p1.getSort() == null && p2.getSort() == null) return 0;
                if (p1.getSort() == null) return 1;
                if (p2.getSort() == null) return -1;
                return p1.getSort().compareTo(p2.getSort());
            })
            .collect(Collectors.toList());
        
        for (Permission child : children) {
            printPermissionNode(child, allPermissions, level + 1);
        }
    }
    
    /**
     * 获取权限类型字符串
     */
    private static String getTypeString(Integer type) {
        if (type == null) return "未知";
        switch (type) {
            case 1: return "菜单";
            case 2: return "按钮";
            case 3: return "API";
            default: return "未知";
        }
    }
    
    /**
     * 统计权限数量
     */
    public static void printPermissionStats(List<Permission> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            System.out.println("权限列表为空");
            return;
        }
        
        long menuCount = permissions.stream().filter(p -> p.getType() == 1).count();
        long buttonCount = permissions.stream().filter(p -> p.getType() == 2).count();
        long apiCount = permissions.stream().filter(p -> p.getType() == 3).count();
        long enabledCount = permissions.stream().filter(p -> p.getStatus() == 1).count();
        long disabledCount = permissions.stream().filter(p -> p.getStatus() == 0).count();
        
        System.out.println("=== 权限统计信息 ===");
        System.out.printf("总权限数: %d%n", permissions.size());
        System.out.printf("菜单权限: %d%n", menuCount);
        System.out.printf("按钮权限: %d%n", buttonCount);
        System.out.printf("API权限: %d%n", apiCount);
        System.out.printf("启用权限: %d%n", enabledCount);
        System.out.printf("禁用权限: %d%n", disabledCount);
        System.out.println("==================");
    }
    
    /**
     * 验证权限树结构
     */
    public static boolean validatePermissionTree(List<Permission> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            return true;
        }
        
        boolean isValid = true;
        
        for (Permission permission : permissions) {
            // 检查父权限是否存在
            if (permission.getParentId() != null) {
                boolean parentExists = permissions.stream()
                    .anyMatch(p -> Objects.equals(p.getId(), permission.getParentId()));
                
                if (!parentExists) {
                    System.err.printf("权限 [%d] %s 的父权限 [%d] 不存在%n", 
                        permission.getId(), permission.getName(), permission.getParentId());
                    isValid = false;
                }
            }
            
            // 检查权限编码是否重复
            long codeCount = permissions.stream()
                .filter(p -> Objects.equals(p.getCode(), permission.getCode()))
                .count();
            
            if (codeCount > 1) {
                System.err.printf("权限编码 %s 重复出现%n", permission.getCode());
                isValid = false;
            }
        }
        
        if (isValid) {
            System.out.println("权限树结构验证通过");
        } else {
            System.err.println("权限树结构验证失败");
        }
        
        return isValid;
    }
    
    /**
     * 生成权限编码列表
     */
    public static void printPermissionCodes(List<Permission> permissions) {
        if (CollectionUtils.isEmpty(permissions)) {
            System.out.println("权限列表为空");
            return;
        }
        
        System.out.println("=== 权限编码列表 ===");
        
        // 按类型分组打印
        System.out.println("菜单权限:");
        permissions.stream()
            .filter(p -> p.getType() == 1)
            .forEach(p -> System.out.printf("  %s - %s%n", p.getCode(), p.getName()));
        
        System.out.println("按钮权限:");
        permissions.stream()
            .filter(p -> p.getType() == 2)
            .forEach(p -> System.out.printf("  %s - %s%n", p.getCode(), p.getName()));
        
        System.out.println("API权限:");
        permissions.stream()
            .filter(p -> p.getType() == 3)
            .forEach(p -> System.out.printf("  %s - %s%n", p.getCode(), p.getName()));
        
        System.out.println("==================");
    }
}